/*
 * stepper_group.c
 *
 *  Created on: Jan 31, 2025
 *      Author: wzx05
 */

#include <Motor\stepper_group.h>
#include <Motor\stepper_cfg.h>
#include <Motor\shift_reg.h>
#include "main.h"

// 移位寄存器状态寄存器
static ShiftReg_Transfer g_shiftTransfers[MOTOR_GROUPS];

// 移位寄存器硬件配置（请根据实际接线修改）
static const ShiftReg_Handle reg_groups[MOTOR_GROUPS] = {
    // Motor Group 0
    {MOTOR_A_SER_GPIO_Port, MOTOR_A_SER_Pin,  // SER
     MOTOR_A_SRCLK_GPIO_Port, MOTOR_A_SRCLK_Pin,  // SRCLK
	 MOTOR_A_RCLK_GPIO_Port, MOTOR_A_RCLK_Pin}, // RCLK
    // Motor Group 1
	{MOTOR_B_SER_GPIO_Port, MOTOR_B_SER_Pin,  // SER
	 MOTOR_B_SRCLK_GPIO_Port, MOTOR_B_SRCLK_Pin,  // SRCLK
	 MOTOR_B_RCLK_GPIO_Port, MOTOR_B_RCLK_Pin}, // RCLK
	// Motor Group 2
	{MOTOR_C_SER_GPIO_Port, MOTOR_C_SER_Pin,  // SER
	 MOTOR_C_SRCLK_GPIO_Port, MOTOR_C_SRCLK_Pin,  // SRCLK
	 MOTOR_C_RCLK_GPIO_Port, MOTOR_C_RCLK_Pin}, // RCLK
	// Motor Group 3
	{MOTOR_D_SER_GPIO_Port, MOTOR_D_SER_Pin,  // SER
	 MOTOR_D_SRCLK_GPIO_Port, MOTOR_D_SRCLK_Pin,  // SRCLK
	 MOTOR_D_RCLK_GPIO_Port, MOTOR_D_RCLK_Pin}, // RCLK
};

void Stepper_InitGroup(uint8_t group) {
    if (group >= MOTOR_GROUPS) return;
    /*
    ShiftReg_Handle hreg = {
        .ser_port = reg_groups[group].ser_port,
        .ser_pin = reg_groups[group].ser_pin,
        .srclk_port = reg_groups[group].srclk_port,
        .srclk_pin = reg_groups[group].srclk_pin,
        .rclk_port = reg_groups[group].rclk_port,
        .rclk_pin = reg_groups[group].rclk_pin
    };
    ShiftReg_Init(&hreg);
    */
    ShiftReg_Init(&reg_groups[group]);
    g_shiftTransfers[group].hreg = &reg_groups[group];
    g_shiftTransfers[group].state = SHIFTREG_STATE_IDLE;
}

void Stepper_WriteGroupAsync(uint8_t group, uint16_t data) {
    if (group >= MOTOR_GROUPS) return;
    //ShiftReg_Write16(&reg_groups[group], data);
    ShiftReg_StartTransfer(&g_shiftTransfers[group], data);
}

void Stepper_WriteGroupSync(uint8_t group, uint16_t data) {
    if (group >= MOTOR_GROUPS) return;
    ShiftReg_Write16(&reg_groups[group], data);
    //ShiftReg_StartTransfer(&g_shiftTransfers[group], data);
}

void Stepper_HomeGroup(uint8_t group) {
    // 根据实际硬件和传感器实现组级归零，此处留空供后续实现
}

void Stepper_EnableGroup(uint8_t group, bool enable) {
    // 根据实际电路（例如使能管脚）实现组级启用或禁用
	// 当前各组使用相同使能引脚，故此处未分组
	if (enable) {
		HAL_GPIO_WritePin(MOTOR_GLB_MR__GPIO_Port, MOTOR_GLB_MR__Pin, GPIO_PIN_RESET);
		HAL_Delay(1);
		HAL_GPIO_WritePin(MOTOR_GLB_MR__GPIO_Port, MOTOR_GLB_MR__Pin, GPIO_PIN_SET);
		HAL_Delay(1);
	}
}

// （基于系统硬中断或集中调度）更新Group配套移位寄存器的输出状态，实现GPIO非阻塞周期输出
void Stepper_UpdateGroupTransfer(uint8_t group) {
    if (group >= MOTOR_GROUPS) return;
    ShiftReg_TransferHandler(&g_shiftTransfers[group]);
}
